<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    table {
      width: 500px;
      margin: 20px auto;
    }

    td {
      text-align: center;
      width: 100px;
    }
  </style>
</head>

<body>
  <table border="1">
    <thead>
      <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>爱好</th>
      </tr>

    </thead>
    <tbody id="mytbody">
      <!-- <tr>
        <td>马云</td>
        <td>50</td>
        <td>男</td>
        <td>对钱没兴趣</td>
      </tr> -->
    </tbody>

  </table>
  <!-- json数据和对象的区别 -->
  <script>
    // var car = {
    //   name: "比亚迪",
    //   color: "红色",
    //   run: function () { }
    // }
    // JSON数据的key值 必须时字符串 
    var car = {
      "name": "比亚迪",
      "color": "红色"
    }

    // 对象的访问
    // document.write(car.name)
    // document.write(car["color"]) //==car.color
    // 常见数据结构

    var arr = [
      {
        "id": +new Date(),
        "isChecked": true,
        "name": 'A1',
        "age": 30,
        "sex": "男",
        "love": "学习",
      }, {
        "id": 1,
        "isChecked": false,
        "name": 'A2',
        "age": 20,
        "sex": "女",
        "love": "健身",
      }, {
        "id": 2,
        "isChecked": true,
        "name": 'A3',
        "age": 40,
        "sex": "女",
        "love": "夜跑",
      }, {
        "id": 3,
        "isChecked": false,
        "name": 'A4',
        "age": 35,
        "sex": "男",
        "love": "睡觉",
      },
      {
        "id": 4,
        "isChecked": false,
        "name": 'A5',
        "age": 35,
        "sex": "男",
        "price": {
          "arr": [{ "size": 1, "age": 2 }, { "size": 2, "age": 9 }]
        },
        "love": "写程序",
      },
    ];
    // document.write(arr[1].love)
    // document.write(arr[4].price.arr[1].age)
    console.log(arr)
    // 1 json 对象转成字符串 JSON.stringify()
    var str = JSON.stringify(arr)
    console.log(str)
    // 2 字符串类型json 转成对象类型的JSON   JSON.parse()
    var newarr = JSON.parse(str)
    console.log(newarr)
    // 循环json数据 动态生成tr
    var str = ""
    for (var i = 0; i < arr.length; i++) {
      str += `
            <tr>
              <td>${arr[i].name}</td>
              <td>${arr[i].age}</td>
              <td>${arr[i].sex}</td>
              <td>${arr[i].love}</td>
            </tr>
        `
    }
    // 把循环生成的tr 放到 tbody中
    var mytbody = document.getElementById("mytbody")
    mytbody.innerHTML = str;
  </script>
</body>

</html>